package opens.components.http;

import java.util.List;

import opens.components.cache.Cache;
import opens.components.http.core.HttpRequest;
import opens.components.http.core.RequestQueue;

import org.apache.http.HttpResponse;

import com.huewu.pla.pinterest.internal.ImageWrapper;
import com.idreems.model.ServerDataDecoder;

public class ChannelRequest extends HttpObjectRequest<List<ImageWrapper>> {
	private ServerDataDecoder mDataDecoder;

	public ChannelRequest(ServerDataDecoder d) {
		mDataDecoder = d;
	}

	@Override
	protected void onHttpResponseReceived(HttpResponse response)
			throws Exception {
		List<ImageWrapper> timeline = mDataDecoder
				.decode(getString(response));
		setResponseObject(timeline);
		//TODO::cache images
		for (ImageWrapper imageWrapper : timeline) {
			cacheImageFromUrl(imageWrapper.url,getCache());
			cacheImageFromUrl(imageWrapper.largeUrl,getCache());
		}
	}
	
	private void cacheImageFromUrl(String url, Cache cache) {
		ImageRequest imageRequest = new ImageRequest();
		imageRequest.setCache(cache);
		imageRequest.setCachePolicy(HttpRequest.FallbackToCacheIfLoadFailsCachePolicy);
		RequestQueue.instanceForLongRequestQueue().push(imageRequest.get(url));
	}	
}
